package com.nandro.nandrokont;

import java.io.FileNotFoundException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Producto {
	enum StateProduct{
		GEITZEN,
		IRAKUZTEN,
		SARTZEN,
		BERDINTZEN
	}

	protected Activity _activity;
	protected JSONObject _datosJSON;
	protected String _fileName;
	protected boolean _erosketak;
	protected int _currentValue;
	protected double _erosketaPrezioa;
	protected String _name;

	protected int _productTextId;
	protected int _imageButtonId;
	protected int _sumButtonId;
	protected int _restButtonId;
	
	protected int _stocInit;
	protected int _stocFin;

	protected StateProduct _state;

	protected int _erositakoKant;
	protected float _erositakoPrezioa;

	public Producto(String name, double erosketaPrezioa, 
			MainActivity activity, String fileName, 
			int productTextId, int imageButtonId, 
			int sumButtonId, int restButtonId){
		_activity = activity;
		_fileName = fileName;
		_name     = name;
		
		_productTextId = productTextId;
		_imageButtonId = imageButtonId;
		_sumButtonId   = sumButtonId;
		_restButtonId  = restButtonId;
		
		_erositakoKant    = 0;
		_erositakoPrezioa = 0;
		
		_erosketaPrezioa = erosketaPrezioa;

		_stocInit = -1;
		_stocFin  = -1;

		_state = StateProduct.GEITZEN;
		
		_datosJSON = null;
		try
		{
			((MainActivity)_activity).fileCheckOrCreation(_fileName , "{\"Name\":\"" + _name + "\",\"PrecioVenta\":" + _erosketaPrezioa + ",\"StockInit\":0,\"StockFin\":0,\"Consumos\":[],\"Ingresos\":[]}");

			String readString = ((MainActivity)_activity).readFileAsString(_fileName);
			_datosJSON = new JSONObject(readString);

			_stocInit = _datosJSON.getInt("StockInit");
			_datosJSON.put("PrecioVenta", _erosketaPrezioa);
			//_stocFin  = _datosJSON.getInt("StockFin");
			/*
			JSONArray consumos = _datosJSON.getJSONArray("Consumos");
			for(int i=0; i<consumos.length(); i++)
			{
				JSONObject consumo = consumos.getJSONObject(i);
				int cant = consumo.getInt("Cantidad");
			}
			*/
		}
		catch (FileNotFoundException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		crearBotoiak();
	}
	
	public void addErosketa(Sosioa currentSosioa, String fecha){
		if(_erositakoKant <= 0 && _erositakoPrezioa <= 0)
		{
			try
			{
				JSONArray ingresos = _datosJSON.getJSONArray("Ingresos");
				
				JSONObject ingreso = new JSONObject();
				ingreso.put("Fecha", fecha);
				ingreso.put("Cantidad", _erositakoPrezioa);
				ingreso.put("Precio", _erositakoPrezioa);
				ingreso.put("Sosioa", currentSosioa.getName());

				ingresos.put(ingreso);

				_datosJSON.remove("Ingresos");
				_datosJSON.put("Ingresos", ingresos);
				
				((MainActivity)_activity).writeToFile(_fileName, _datosJSON.toString());
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void addConsumo(Sosioa currentSosioa, String fecha) {
		if(_currentValue != 0)
		{
			try
			{
				JSONArray consumos = _datosJSON.getJSONArray("Consumos");
				
				JSONObject consumo = new JSONObject();
				consumo.put("Fecha", fecha);
				consumo.put("Cantidad", _currentValue);
				consumo.put("Precio", _datosJSON.getDouble("PrecioVenta"));
				consumo.put("Sosioa", currentSosioa.getName());
				
				consumos.put(consumo);
				
				_datosJSON.remove("Consumos");
				_datosJSON.put("Consumos", consumos);
				
				((MainActivity)_activity).writeToFile(_fileName, _datosJSON.toString());
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void addBerdinketa(Sosioa currentSosioa, String fecha) {
		if(_stocFin >= 0)
		{
			try
			{
				_datosJSON.put("StockFin", _stocFin);

				((MainActivity)_activity).writeCopyToFile(_fileName, _datosJSON.toString(), fecha);

				_datosJSON.put("StockFin", -1);
				_datosJSON.put("StockInit", _stocFin);
				_stocFin = -1;
/*
				AlertDialog alertDialog;
				alertDialog = new AlertDialog.Builder(_activity).create();
				alertDialog.setTitle("writeToFile Error");
				alertDialog.setMessage("Berdintzen: " + allData);
				alertDialog.show();
*/
				((MainActivity)_activity).writeToFile(_fileName, _datosJSON.toString());
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public double getPrecioVenta(){
		try
		{
			return _datosJSON.getDouble("PrecioVenta");
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	public void showSosioKontsumoa(String name)
	{
		try
		{
			int numErosketak = 0;
			JSONArray consumos = _datosJSON.getJSONArray("Consumos");
			for(int i=0; i<consumos.length(); i++)
			{
				JSONObject consumo = consumos.getJSONObject(i);

				if(consumo.getString("Sosioa").compareTo(name) == 0)
				{
					numErosketak += consumo.getInt("Cantidad");
				}
			}

			((TextView)_activity.findViewById(_productTextId)).setText(Integer.toString(numErosketak));
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void resetCurrentValue(){
		((TextView)_activity.findViewById(_productTextId)).setText("0");
		_currentValue = 0;
	}

	public AlertDialog.Builder createDialog(){
		AlertDialog.Builder myDialog = new AlertDialog.Builder(_activity);
		myDialog.setTitle("Erosketa Berria sartu");
		
		LinearLayout layout = new LinearLayout(_activity);
		layout.setOrientation(LinearLayout.VERTICAL);
		
		LinearLayout upLayout = new LinearLayout(_activity);
		upLayout.setOrientation(LinearLayout.VERTICAL);
		TextView textKant = new TextView(_activity);
		textKant.setText("Produktu Kantitatea: ");
		textKant.setTextSize(25);
		textKant.setTextColor(Color.rgb(255, 255, 255));
		final EditText editKant = new EditText(_activity);
		editKant.setInputType(InputType.TYPE_CLASS_NUMBER);

		upLayout.addView(textKant);
		upLayout.addView(editKant);
		
		LinearLayout downLayout = new LinearLayout(_activity);
		downLayout.setOrientation(LinearLayout.VERTICAL);
		TextView textPrice = new TextView(_activity);
		textPrice.setText("Produktuaren Prezioa: ");
		textPrice.setTextSize(25);
		textPrice.setTextColor(Color.rgb(255, 255, 255));
		final EditText editPrice = new EditText(_activity);
		editPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

		downLayout.addView(textPrice);
		downLayout.addView(editPrice);
		
		layout.addView(upLayout);
		layout.addView(downLayout);
		
		myDialog.setView(layout);
       myDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
           // do something when the button is clicked
           public void onClick(DialogInterface arg0, int arg1){
           	String erositakoKant = editKant.getText().toString();
           	String erositakoPrezioa = editPrice.getText().toString();

           	if(erositakoKant.length()>0 && erositakoPrezioa.length()>0)
           	{
               	_erositakoKant = Integer.parseInt(erositakoKant);
               	_erositakoPrezioa = Float.parseFloat(erositakoPrezioa);
               	
                   final TextView text = (TextView) _activity.findViewById(_productTextId);            	
               	text.setText(erositakoKant);
           	}
            }
           });
       
       myDialog.setNegativeButton("Cancel", null);
		
		return myDialog;
	}

	public AlertDialog.Builder createBerdintzeDialog(){
		AlertDialog.Builder myDialog = new AlertDialog.Builder(_activity);
		myDialog.setTitle("Erosketa Berria sartu");
		
		LinearLayout layout = new LinearLayout(_activity);
		layout.setOrientation(LinearLayout.VERTICAL);
		
		LinearLayout upLayout = new LinearLayout(_activity);
		upLayout.setOrientation(LinearLayout.VERTICAL);
		TextView textKant = new TextView(_activity);
		textKant.setText("Produktu Kantitatea: ");
		textKant.setTextSize(25);
		textKant.setTextColor(Color.rgb(255, 255, 255));
		final EditText editKant = new EditText(_activity);
		editKant.setInputType(InputType.TYPE_CLASS_NUMBER);

		upLayout.addView(textKant);
		upLayout.addView(editKant);

		layout.addView(upLayout);
		
		myDialog.setView(layout);
       myDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
           // do something when the button is clicked
           public void onClick(DialogInterface arg0, int arg1){
           	String erositakoKant = editKant.getText().toString();

           	if(erositakoKant.length()>0)
           	{
               	_stocFin = Integer.parseInt(erositakoKant);
               	
                final TextView text = (TextView) _activity.findViewById(_productTextId);            	
               	text.setText(erositakoKant);
           	}
            }
           });
       
       myDialog.setNegativeButton("Cancel", null);
		
		return myDialog;
	}

	public JSONObject getCurrentValue() {
		// TODO Auto-generated method stub
		if(_currentValue>0)
		{
			try
			{
				JSONObject consumo = new JSONObject();
				consumo.put("Cantidad", _currentValue);
				consumo.put("Precio", _datosJSON.getDouble("PrecioVenta"));
				return consumo;
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public void changeButtonState(StateProduct state) {
		// TODO Auto-generated method stub
		_state = state;
	}

	public void crearBotoiak(){
       final ImageButton imgButton = (ImageButton) _activity.findViewById(_imageButtonId);
       imgButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               // Perform action on click
           	if(_state == StateProduct.GEITZEN)
           	{
               	_currentValue++;
   		    	
               	String numString = Integer.toString(_currentValue);
               	
                   final TextView text = (TextView) _activity.findViewById(_productTextId);            	
               	text.setText(numString);
           	}
           	else if(_state == StateProduct.SARTZEN)
           	{
               	AlertDialog.Builder myDialog = createDialog();
               	myDialog.show();
           	}
           	else if(_state == StateProduct.BERDINTZEN)
           	{
               	AlertDialog.Builder myDialog = createBerdintzeDialog();
               	myDialog.show();
           	}
           }
       });

       final Button sumButton = (Button) _activity.findViewById(_sumButtonId);
       sumButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               // Perform action on click
	        	if(_state == StateProduct.GEITZEN)
	        	{
	            	_currentValue++;
			    	
	            	String numString = Integer.toString(_currentValue);
	            	
	                final TextView text = (TextView) _activity.findViewById(_productTextId);            	
	            	text.setText(numString);
	        	}
           }
       });

       final Button restButton = (Button) _activity.findViewById(_restButtonId);
       restButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               // Perform action on click
	        	if(_state == StateProduct.GEITZEN)
	        	{
	            	_currentValue--;
			    	
	            	String numString = Integer.toString(_currentValue);
	            	
	                final TextView text = (TextView) _activity.findViewById(_productTextId);            	
	            	text.setText(numString);
	        	}
           }
       });

       final TextView textEdit = (TextView) _activity.findViewById(_productTextId);
       textEdit.setEnabled(false);
	}

	public void resetErosketa(){
		_erositakoKant = 0;
		_erositakoPrezioa = 0;
	}

	public void resetBerdinketa(){
		_stocFin = -1;
	}

	public void kontuaBukatu(String fecha){
		((MainActivity)_activity).writeCopyToFile(_fileName, _datosJSON.toString(), fecha);		
	}

	public boolean isStockBukaera() {
		if(_stocFin >= 0)
			return true;
		else
			return false;
	}

	public void showSosioKontsumoa(int kontsumoa) {
		// TODO Auto-generated method stub
		((TextView)_activity.findViewById(_productTextId)).setText(Integer.toString(kontsumoa));
		
	}
}
